﻿/*-------------------------------------------------------------------------
* 命名空间: WaferSelectV3.Common/FileOperateHelper
* 类       名: FileOperateHelper
* 功      能:  TD
* 时      间:  2024-05-10 14:46:53
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using Microsoft.IdentityModel.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WaferSelectV3.Extensions;

namespace WaferSelectV3.Common
{
    public class FileOperateHelper
    {
        /// <summary>
        /// 根据文件路径创建一个空文件,如果文件已经存在则清空文件内容.
        /// </summary>
        /// <param name="filePath"></param>
        public static void CreateAnEmptyFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                }
                using (StreamWriter sw = new StreamWriter(filePath, false)) { }
                File.SetAttributes(filePath, FileAttributes.ReadOnly);
            }
            catch (Exception ex)
            {
                LoggerHelper.WriteLogMain($"文件 <{filePath}> 创建失败,失败原因: {ex.GetFullException()}", LogType.Exception);
            }

        }

        /// <summary>
        /// 以追加的方式写入内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        public static void WriteToFileAppend(string filePath, string content)
        {
            File.SetAttributes(filePath, FileAttributes.Normal);
            using (StreamWriter sw = new StreamWriter(filePath, true))
            {
                sw.WriteLine(content);
            }
            File.SetAttributes(filePath, FileAttributes.ReadOnly);
        }

        /// <summary>
        /// 文件是否已经被占用,通过读取文件的方式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsFileLocked(string filePath)
        {
            try
            {
                using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return true;
            }
        }
    }
}
